import { CloseCircleOutlined } from '@ant-design/icons';
import { Button, Input, message, Switch, TableColumnsType, TableProps } from 'antd';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useMemo, useState } from 'react';

import orgService from '@/api/services/orgService';
import {
  CreateGroupReq,
  CreateUserReq,
  GetGroupTreeList,
  GetOrgGroupUserInfoReq,
  GetOrgGroupUserInfoRes,
  GetRoleRes,
  GroupUserInfoList,
  UpdateGroupReq,
} from '@/common/types';
import { SvgIcon } from '@/components/icon';
import { CircleLoading } from '@/components/loading';
import TipsModals from '@/components/modals/TipsModals';
import NotData from '@/components/NotData';
import Tables from '@/components/tables/tables';
import TipDesc from '@/components/tipDesc/tipDesc';
import useDragResize from '@/hooks/use-drag-resize';
import useModal from '@/hooks/use-modal/useModal';
import { useConfigActions, useInitializeData, useOrgManageTree } from '@/store/configStore';
import { StorageEnum } from '@/types/enum';
import { hashStr, checkPasswordStrength } from '@/utils/hashStr';
import { getItem } from '@/utils/storage';
import { formatData } from '@/utils/time';

import AddOrDditOrganiztionalModal from './components/add-or-edit-organiztional-modal/add-or-edit-organiztional-modal';
import ChangePasswordModal from './components/change-password-modal/change-password-modal';
import OrganizationalTree, {
  TreeClickType,
} from './components/organizational-tree/organizational-tree';
import UpdateModal from './components/update-modal/update-modal';
import './styles.scss';

interface orgDefaultData {
  id?: string;
  name: string;
  parent_id: string;
  description: string;
  level?: number;
}

interface GroupUserForm extends CreateUserReq {
  id: string;
  is_tiangong?: boolean; // 新增该字段，与前端传递的参数匹配
}

type DeleteModalType = 'all' | 'org' | 'user';

const OrganizationalManage = () => {
  const modal = useModal('update', 'import', 'orgModal', 'deleteModal', 'passwordModal');

  const { activeValue, expandedKeys } = useOrgManageTree();

  const { setOrgManageTree } = useConfigActions();

  const [resizeWidth, handleMouseDown] = useDragResize({ width: 344, maxWidth: 480 });

  const { license_edition, allowLocalAccount } = useInitializeData();
  const isLocalAccount = useMemo(() => {
    if (!license_edition) {
      return false;
    }
    return !!allowLocalAccount;
  }, [allowLocalAccount, license_edition]);
  // 天工角色权限
  const currentUser = getItem<any>(StorageEnum.User);
  const isTiangongSuperAdmin = Boolean(
    currentUser?.is_TianGong === true && currentUser?.role?.code === 'super_admin',
  );

  // 角色列表
  const [roleList, setRoleList] = useState<GetRoleRes[]>([]);

  // 分页信息
  const [pagingInfo, setPagingInfo] = useState({
    page: 1,
    page_size: 10,
    searchText: '',
    total: 0,
  });

  // 表格信息
  const [tablesValue, setTablesValue] = useState<GetOrgGroupUserInfoRes['list']>([]);

  // 树形组织数据
  const [treeData, setTreeData] = useState<GetGroupTreeList[]>([]);

  // 默认树形组织数据
  const [treeDataDefault, setTreeDataDefault] = useState<GetGroupTreeList[]>([]);

  // true 为添加组织 false 为编辑组织
  const [treeUpdateorEditState, setTreeUpdateorEditState] = useState<boolean>(false);

  // 删除弹窗状态 org为删除组织 all为批量删除用户 user为删除单个用户
  const [isDeleteModalState, setIsDeleteModalState] = useState<DeleteModalType>();

  // 删除数据
  const [isDeleteId, setIsDeleteId] = useState<string>('');

  // table选中的数据id
  const [tableSelectEdRows, setTableSelectEdRows] = useState<React.Key[]>([]);

  // 添加或修改组织默认数据
  const [organiztionalModalDefaultData, setOrganiztionalModalDefultData] =
    useState<orgDefaultData>();

  const [organiztionalModalOption, setOrganiztionalModalOption] = useState<GetGroupTreeList[]>([]);

  // 新增/修改用户弹窗 新增为true 修改为false
  const [updateModalState, setUpdateModalState] = useState<boolean>(true);

  // 新增/修改默认数据
  const [updateModalDefaultValue, setUpdateModalDefaultValue] = useState<GroupUserForm>();

  // 修改密码的id
  const [passwordId, setPasswordId] = useState<string>('');

  const [searchValue, setSearchValue] = useState<string>('');

  const [searchUserValue, setSearchUserValue] = useState<string>('');

  const [searchLoading, setSearchLoading] = useState<boolean>(false);

  const [groupLoading, setGroupLoading] = useState<boolean>(false);

  const [userLoading, setUserLoading] = useState<boolean>(false);

  const [userSwitchLoading, setUserSwitchLoading] = useState<string[]>([]);

  const [userSystemCode, setUserSystemCode] = useState<string>('');

  useEffect(() => {
    setGroupLoading(true);
    setUserLoading(true);
    getGroup();
    getRole();
  }, []);

  const getRole = () => {
    orgService.getRole().then((res) => {
      setRoleList(res);
    });
  };

  const findNode = (tree: GetGroupTreeList[], id: string): GetGroupTreeList | null => {
    for (const node of tree) {
      if (node.id === id) {
        return node; // 找到目标节点
      }
      if (node.children && node.children.length > 0) {
        const result = findNode(node.children, id); // 递归查找子节点
        if (result) {
          return result;
        }
      }
    }
    return null; // 未找到
  };

  const getGroup = (value?: string, change?: boolean) => {
    setGroupLoading(true);
    orgService
      .getOrgGroupTreeList(value)
      .then((res) => {
        if (res.length === 0) {
          setTreeData([]);
          setTreeDataDefault([]);
          return;
        }

        const temp = res.filter((item) => item.system_code !== 'default');

        if (!value) {
          setTreeDataDefault(temp);
          setSearchLoading(false);
        }

        if (value) {
          setTreeData(temp);
          setSearchLoading(true);
          return;
        }

        if (!activeValue) {
          setOrgManageTree(temp[0]);
        }

        if (activeValue && activeValue.id) {
          const temp = findNode(res, activeValue?.id);
          if (temp) {
            setOrgManageTree(temp, change);
          } else {
            setOrgManageTree(res[0], change);
          }
        }

        setTreeData(temp);
      })
      .catch((e) => {
        console.log(e);
      })
      .finally(() => {
        setGroupLoading(false);
      });
  };

  useEffect(() => {
    let value;
    if (activeValue) {
      const paging = {
        page: 1,
        page_size: 10,
        searchText: '',
        total: 0,
      };
      value = { ...paging, group_id: activeValue.id };
    }

    if (value) {
      getUser(value);
    }
  }, [activeValue]);

  /**
   * @description: 表格多选
   * @return {*}
   */
  const rowSelection: TableProps<GroupUserInfoList>['rowSelection'] = {
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setTableSelectEdRows(newSelectedRowKeys);
    },
    getCheckboxProps: (record: GroupUserInfoList) => ({
      disabled: record.name === 'root', // Column configuration not to be checked
    }),
  };

  const columns: TableColumnsType<GroupUserInfoList> = [
    {
      title: isTiangongSuperAdmin ? '邮箱' : '名称',
      dataIndex: 'name',
      render: (_, { name }) => name || '-',
    },
    ...(isTiangongSuperAdmin
      ? []
      : [
          {
            title: '学/工号',
            dataIndex: 'user_id',
            // render: (_, { user_id }) => <div className="truncate">{user_id ? user_id : '-'}</div>,
            render: (_, { user_id }) => <div>{user_id || '-'}</div>,
          },
        ]),
    {
      title: '所属组织',
      dataIndex: 'group',
      render: (_, { group }) => <div className="truncate">{group.name ? group.name : '-'}</div>,
    },
    {
      title: '角色',
      width: 120,
      dataIndex: 'role',
      render: (_, { role }) => <div>{role ? role.name : '-'}</div>,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      render: (_, { create_time }) => <div>{create_time ? formatData(create_time) : '-'}</div>,
    },
    {
      title: '账号启/停状态',
      width: 120,
      dataIndex: 'status',
      render: (_, record) => (
        <Switch
          checked={record.status}
          onClick={() => handleUserState(record.id)}
          loading={userSwitchLoading.some((item) => item === record.id)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 244,
      render: (_, record) => {
        const disabled = record.name === 'root';

        return (
          <div className="flex">
            <a
              className={`mr-3 flex items-center ${
                disabled ? '!cursor-not-allowed !text-@brand-color-disabled' : '!text-@brand-color'
              }
              `}
              onClick={() => (disabled ? undefined : openUpdateModal('edit', record))}
            >
              <SvgIcon icon="message-ic12" size="16px" className="mr-1" />
              编辑
            </a>
            {isLocalAccount && (
              <a
                className={`mx-3 flex items-center ${
                  disabled
                    ? '!cursor-not-allowed !text-@brand-color-disabled'
                    : '!text-@brand-color'
                }`}
                onClick={() => (disabled ? undefined : openChangePasswordModal(record.id))}
              >
                <SvgIcon icon="lock" size="16px" className="mr-1" />
                修改密码
              </a>
            )}
            <a
              className={`ml-3 flex items-center ${
                disabled ? `!cursor-not-allowed !text-@error-color-disabled` : '!text-@error-color'
              }
              `}
              onClick={() => (disabled ? undefined : openDeleteModal('user', record.id))}
            >
              <SvgIcon icon="message-ic3" size="16px" className="mr-1" />
              删除
            </a>
          </div>
        );
      },
    },
  ];

  /**
   * @description: 清除选中表格数据
   */
  const clearTableSelectEdRows = () => {
    setTableSelectEdRows([]);
  };

  /**
   * @description: 打开修改密码弹窗
   * @param {string} id 修改密码的id值
   * @return {*}
   */
  const openChangePasswordModal = (id: string) => {
    modal.passwordModal.open();
    setPasswordId(id);
  };

  /**
   * @description: 关闭修改密码弹窗
   * @return {*}
   */
  const closeChangePasswordModal = () => {
    modal.passwordModal.stopLoading();
    modal.passwordModal.close();
    setPasswordId('');
  };

  /**
   * @description: 修改密码弹窗提交
   * @param {*} value 新密码值
   * @return {*}
   */
  const changePasswordModalSubmit = (value: any) => {
    if (value.password !== value.confirmPassword) {
      message.error('两次密码输入不一致');
      return;
    }

    if (!checkPasswordStrength(value.password)) {
      message.error('密码必须包含大写字母、小写字母、数字、特殊符号中的至少三种且长度8位以上');
      return;
    }

    modal.passwordModal.startLoading();
    orgService
      .updateUserPassword({ id: passwordId, password: hashStr(value.password) })
      .then(() => {})
      .finally(() => {
        closeChangePasswordModal();
      });
  };

  /**
   * @description: 打开新增用户弹窗
   * @return {*}
   */
  const openUpdateModal = (type: 'edit' | 'update', value?: GroupUserInfoList) => {
    console.log('xiaY__', { type, value });
    if (type === 'edit' && value) {
      setUserSystemCode(value.group.system_code ? value.group.system_code : '');
      setUpdateModalDefaultValue({
        id: value.id,
        name: value.name,
        user_id: value.user_id || value.name,
        group_id: value.group.id,
        role_code: value.role ? value.role.code : '',
        status: value.status,
        password: '',
      });
    } else {
      let groupId = '';
      if (activeValue && activeValue?.system_code !== 'root') {
        groupId = activeValue?.id;
      }
      setUserSystemCode('');

      const nextDefaults = {
        id: '',
        name: '',
        user_id: '',
        group_id: groupId.length > 0 ? groupId : undefined,
        password: '',
        role_code: 'normal_user',
        status: true,
        is_tiangong: !!isTiangongSuperAdmin,
      } as any;
      setUpdateModalDefaultValue(nextDefaults);
    }

    setUpdateModalState(type === 'update');
    setOrganiztionalModalOption(treeData);
    // setOrganiztionalModalOption(flattenTree(treeData, 3));
    modal.update.open();
  };

  /**
   * @description: 提交弹窗信息
   * @return {*}
   */
  const updateModalSubmit = (value: any, id?: string) => {
    modal.update.startLoading();
    if (updateModalState) {
      if (isLocalAccount && !checkPasswordStrength(value.password)) {
        message.error('密码必须包含大写字母、小写字母、数字、特殊符号中的至少三种且长度8位以上');
        modal.update.stopLoading();
        return;
      }

      // 天工超级管理员新增用户：隐藏了学/工号输入，但接口仍需 user_id，与 name 一致
      if (isTiangongSuperAdmin) {
        value = {
          ...value,
          user_id: value?.name,
        };
      }

      value = {
        ...updateModalDefaultValue,
        ...value,
        password: isLocalAccount ? hashStr(value.password) : '',
      };
      orgService
        .createUser(value)
        .then(() => {
          getUser({ ...pagingInfo, searchText: '', group_id: activeValue?.id });
          getGroup('', true);
        })
        .finally(() => {
          modal.update.stopLoading();
          modal.update.close();
        });
    } else {
      // 天工超级管理员编辑用户：后端需要 user_id，若未携带则使用 name 补齐
      let updatePayload = value;
      if (isTiangongSuperAdmin && !value?.user_id) {
        updatePayload = { ...value, user_id: value?.name };
      }
      orgService
        .updateUser(updatePayload, id as string)
        .then((res) => {
          setTablesValue((prev) => {
            return prev.map((item) => {
              if (item.id === id) {
                return res;
              }
              return item;
            });
          });
          getGroup('', true);
        })
        .finally(() => {
          modal.update.stopLoading();
          modal.update.close();
        });
    }
  };

  /**
   * @description: 开启删除弹窗
   * @return {*}
   */
  const openDeleteModal = (type: DeleteModalType, id?: string) => {
    setIsDeleteId(id as string);
    setIsDeleteModalState(type);
    modal.deleteModal.open();
  };

  /**
   * @description: 删除组
   * @param {GetGroupTreeList} value 删除的值
   * @param {GetGroupTreeList} treeData 原数组
   * @return {*}
   */
  const deleteGroup = (value: GetGroupTreeList, treeData: GetGroupTreeList[]) => {
    for (let i = 0; i < treeData.length; i++) {
      const element = treeData[i];
      if (element.id === value.id) {
        treeData.splice(i, 1);
        return treeData;
      }
      if (element.children) {
        deleteGroup(value, element.children);
      }
    }
    return treeData;
  };

  const deleteGroupTree = (isDeleteId: string) => {
    // Helper function: recursively search the tree for the item and its parent
    function searchTree(
      nodes: GetGroupTreeList[],
      id: string,
      parent: GetGroupTreeList | null = null,
    ): {
      item: GetGroupTreeList | null;
      parent: GetGroupTreeList | null;
      siblingIndex?: number;
    } | null {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === id) {
          return { item: nodes[i], parent, siblingIndex: i };
        }
        if (nodes[i].children && nodes[i].children.length > 0) {
          const result = searchTree(nodes[i].children, id, nodes[i]);
          if (result) {
            return result;
          }
        }
      }
      return null;
    }

    // Start looking for the node
    const result = searchTree(treeData, isDeleteId);

    if (!result || !result.item) {
      return null; // ID not found in the tree
    }

    const { parent, siblingIndex } = result;

    if (siblingIndex !== undefined && siblingIndex > 0 && parent) {
      // Return the previous sibling
      return parent.children[siblingIndex - 1];
    }
    // Return the parent if no previous sibling exists
    return parent;
  };

  /**
   * @description: 提交删除弹窗信息
   * @return {*}
   */
  const deleteModalSubmit = () => {
    modal.deleteModal.startLoading();

    if (isDeleteModalState === 'org') {
      orgService
        .deleteOrgGroup(isDeleteId)
        .then((res) => {
          const temp = JSON.parse(JSON.stringify(treeData));
          const result = deleteGroup(res, temp);
          if (activeValue?.id === isDeleteId) {
            const deleteData = deleteGroupTree(isDeleteId);
            if (deleteData) {
              setOrgManageTree(deleteData, deleteData.children.length > 0);
            }
          }
          setTreeData(result);
        })
        .finally(() => {
          modal.deleteModal.stopLoading();
          modal.deleteModal.close();
        });
      return;
    }

    let data = { ids: [isDeleteId] };

    if (isDeleteModalState === 'all' && tableSelectEdRows.length > 0) {
      data = { ids: tableSelectEdRows as string[] };
    }

    orgService
      .deleteUser(data)
      .then(() => {
        if (activeValue) {
          getUser({ ...pagingInfo, group_id: activeValue.id });
          setTableSelectEdRows([]);
        }
        getGroup();
        getRole();
      })
      .finally(() => {
        modal.deleteModal.stopLoading();
        modal.deleteModal.close();
      });
  };

  /**
   * @description: 增加数组
   * @param {GetGroupTreeList} value 增加的值
   * @param {GetGroupTreeList} treeData 原数组
   * @return {*}
   */
  const findParent = (
    value: GetGroupTreeList,
    treeData: GetGroupTreeList[],
  ): GetGroupTreeList[] => {
    return treeData.map((node) => {
      // 如果当前节点的 id 与传入的 value.parent_id 匹配
      if (node.id === value.parent_id) {
        // 创建一个新的节点副本，插入新的子节点
        return {
          ...node,
          children:
            node.level === 0
              ? node.children.toSpliced(node.children.length - 1, 0, value)
              : [...(node.children || []), value], // 如果没有 children 初始化为空数组
        };
      }

      // 如果当前节点有子节点，递归处理子节点，返回更新后的副本
      if (node.children && node.children.length > 0) {
        return {
          ...node,
          children: findParent(value, node.children),
        };
      }

      // 如果没有匹配或子节点，直接返回当前节点副本
      return { ...node };
    });
  };

  /**
   * @description: 替换自身
   * @param {GetGroupTreeList} value 替换的值
   * @param {GetGroupTreeList} treeData 原数组
   * @return {*}
   */
  const replaceOneself = (
    value: GetGroupTreeList,
    treeData: GetGroupTreeList[],
  ): GetGroupTreeList[] => {
    return treeData.map((node) => {
      if (node.id === value.id) {
        return value;
      }
      if (node.children && node.children.length > 0) {
        return {
          ...node,
          children: replaceOneself(value, node.children),
        };
      }
      return {
        ...node,
      };
    });
  };

  /**
   * @description: 提交新增或修改弹窗信息
   * @return {*}
   */
  const organiztionalModalSubmit = (value: CreateGroupReq | UpdateGroupReq, type: boolean) => {
    modal.orgModal.startLoading();
    if (type) {
      orgService
        .createOrgGroup(value)
        .then(() => {
          // const result = findParent(res, treeData);
          // setTreeData(result);
          getGroup('', true);
        })
        .finally(() => {
          modal.orgModal.stopLoading();
          modal.orgModal.close();
        });
    } else {
      // console.log(value);

      orgService
        .updateOrgGroup(value as UpdateGroupReq)
        .then(() => {
          getGroup('', true);
        })
        .finally(() => {
          modal.orgModal.stopLoading();
          modal.orgModal.close();
        });
    }
  };

  /**
   * @description: 格式化树形结构
   * @param {GetGroupTreeList[]} treeData 需要格式化的数据
   * @param {number} flattenNumber 需要格式化的层数
   * @param {number} level 当前层数
   * @return {GetGroupTreeList[]} 最深对应层级的数据
   */
  const flattenTree = (
    treeData: GetGroupTreeList[],
    flattenNumber = 0,
    level = 0,
  ): GetGroupTreeList[] => {
    if (level >= flattenNumber) {
      // 如果当前层级已经达到指定层级，直接返回空数组
      return [];
    }

    return treeData.map((node) => {
      // 如果还有子节点并且未达到指定层级，则递归缩减数据到指定层级
      return {
        ...node,
        children: node.children ? flattenTree(node.children, flattenNumber, level + 1) : [],
      };
    });
  };

  /**
   * @description: 树形结构点击事件
   * @param {GetGroupTreeList} value 树形数据
   * @param {TreeClickType} type 点击类型
   * @return {*}
   */
  const handleTreeClick = (value: GetGroupTreeList, type: TreeClickType) => {
    const { name, parent_id, description, id, level } = value;
    if (type === 'update') {
      setTreeUpdateorEditState(true);
      setOrganiztionalModalDefultData({ name: '', parent_id: id, description: '' });
      setOrganiztionalModalOption(flattenTree(treeData, 2));
      modal.orgModal.open();
    } else if (type === 'edit') {
      setTreeUpdateorEditState(false);
      setOrganiztionalModalDefultData({ name, parent_id, description, id, level });
      setOrganiztionalModalOption(flattenTree(treeData, 3));
      modal.orgModal.open();
    } else if (type === 'delete') {
      openDeleteModal('org', value.id);
    } else {
      setOrgManageTree(value, type === 'default', !(type === 'open'));
      if (searchValue.length > 0) {
        setTreeData(treeDataDefault);
        setSearchLoading(false);
      }

      setSearchValue('');
      setSearchUserValue('');
    }
  };

  const getIntersection = (arr1: GroupUserInfoList[], arr2: React.Key[]) => {
    return arr1.filter((item) => arr2.includes(item.id)).map((item) => item.id);
  };

  /**
   * @description: 获取用户信息
   * @param {GetOrgGroupUserInfoReq} value
   * @return {*}
   */
  const getUser = (value: GetOrgGroupUserInfoReq) => {
    setUserLoading(true);
    orgService
      .getUser({ ...value, source: 'system' })
      .then((res) => {
        setTablesValue(res.list);

        const result = getIntersection(res.list, tableSelectEdRows);
        setTableSelectEdRows(result);

        setPagingInfo((prev) => {
          return {
            ...prev,
            total: res.total,
            page_size: res.page_size,
            page: value.page,
            // searchText: value.searchText,
          };
        });
      })
      .finally(() => {
        setUserLoading(false);
      });
  };

  /**
   * @description: 修改用户状态
   * @param {string} id 用户id
   * @return {*}
   */
  const handleUserState = (id: string) => {
    setUserSwitchLoading([...userSwitchLoading, id]);
    orgService
      .updateUserState(id)
      .then(() => {
        setTablesValue((prev) => {
          return prev.map((item) => {
            if (item.id === id) {
              return { ...item, status: !item.status };
            }
            return item;
          });
        });
      })
      .finally(() => {
        setUserSwitchLoading(userSwitchLoading.filter((item) => item !== id));
      });
  };

  /**
   * @description: 改变页码或每页条数
   * @param {number} page 页码
   * @param {number} pageSize 每页条数
   * @return {*}
   */
  const handlePaginationChange = (page: number, pageSize: number) => {
    if (activeValue) {
      getUser({ ...pagingInfo, page, page_size: pageSize, group_id: activeValue.id });
    }
  };

  const searchUser = (e: React.ChangeEvent<HTMLInputElement>) => {
    const result = { ...pagingInfo, searchText: e.target.value, group_id: activeValue?.id };
    setSearchUserValue(e.target.value);
    debounceSearch(result);
  };

  // const debounceSerachUser = (result: any) => {
  //     getUser(result);
  // };

  const debounceSearch = useCallback(
    debounce((result: any) => {
      getUser(result);
    }, 500),
    [],
  );

  const removeDefaultSystemCode = (tree: GetGroupTreeList[]) => {
    // 递归删除指定项和过滤子元素
    return tree
      .map((node) => {
        const newNode = { ...node };
        if (newNode.children) {
          newNode.children = removeDefaultSystemCode(newNode.children);
        }
        return newNode;
      })
      .filter((item) => item.system_code !== 'default' && item.level < 2);
  };

  const findParentName = (targetId?: string): string | null => {
    if (!targetId) return null;

    // 定义递归函数来查找目标 ID 的父级
    function searchNode(node: GetGroupTreeList, targetId: string): string | null {
      if (!node.children || node.children.length === 0) return null;

      for (const child of node.children) {
        if (child.id === targetId) {
          return node.name; // 找到目标 ID 的父级，返回父级的 name
        }
        // 递归继续寻找
        const result = searchNode(child, targetId);
        if (result) return result;
      }
      return null;
    }

    // 从根组织开始查找
    for (const rootNode of treeDataDefault) {
      const result = searchNode(rootNode, targetId);
      if (result) return result;
    }

    return null; // 如果没有找到，返回 null
  };

  const debounceSearchGroupValue = useCallback(
    debounce((value: string) => {
      getGroup(value);
    }, 500),
    [],
  );

  const searchGroup = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setSearchValue(value);
    debounceSearchGroupValue(value);
  };

  return (
    <div className="flex min-h-full flex-col">
      {/* <PagesHeader>组织管理</PagesHeader> */}
      <div className="flex h-full flex-1">
        <div
          className="h-[calc(100vh-16px)] overflow-hidden rounded-xl bg-white"
          // className="box min-w-[240px] max-w-[480px] rounded-default bg-[#F7F8FA] pt-2"
          style={{
            width: resizeWidth,
          }}
        >
          <div className="mb-4 ml-4 mt-4 text-base font-font-weight-600 text-text-5">
            组织管理
            <TipDesc title="用于管理企业或学校的组织架构、人员信息及权限分配" />
          </div>
          <div className="px-3">
            <Input
              placeholder="搜索"
              suffix={<SvgIcon icon="work-ic6" size={16} />}
              onChange={searchGroup}
              style={{
                // borderColor: '#C9CEE2',
                marginBottom: '10px',
              }}
              value={searchValue}
            />
          </div>

          {groupLoading ? (
            <CircleLoading />
          ) : (
            <div className="scrollbar overflow-y-auto" style={{ maxHeight: 'calc(100% - 110px)' }}>
              {treeData.length > 0 ? (
                <OrganizationalTree
                  treeData={treeData}
                  onClick={handleTreeClick}
                  activeKey={activeValue?.id}
                  expandedKeys={expandedKeys}
                  expandedStatus={searchLoading}
                  findParentName={findParentName}
                  resizeWidth={resizeWidth}
                />
              ) : (
                <div className="text-center text-base text-[#A5A9BB]">暂无数据</div>
              )}
            </div>
          )}
          {/* </>
          )} */}
        </div>

        {/* <div className="flex w-4 items-center justify-center bg-bg-1 opacity-0 hover:opacity-100" onMouseDown={handleMouseDown}>
          <div className="h-full w-[2px] cursor-col-resize rounded-default bg-line-2 py-2" />
        </div> */}

        <div
          className="group flex w-4 cursor-col-resize items-center justify-center bg-bg-1 py-2"
          onMouseDown={handleMouseDown}
        >
          <div className="hidden h-full  w-[2px] rounded-default bg-line-2 py-2 group-hover:block" />
        </div>

        <div className="flex h-[calc(100vh-16px)] flex-1 flex-col overflow-y-auto rounded-xl bg-white px-6">
          {/* {userLoading ? (
            <CircleLoading />
          ) : (
            <> */}
          <div className="my-4 flex flex-col items-start justify-between">
            <div className="flex items-center">
              <div className="text-text-5">
                <span className="text-cn-16-blod">{activeValue?.name}</span>
                <span className="text-cn-16">
                  {activeValue && activeValue?.user_count > 0 && `（${activeValue?.user_count}）`}
                </span>
              </div>
            </div>
            <TipDesc title="当前选中的组织或个人的名称" />

            <div className="mt-4 flex w-full">
              <Input
                placeholder="搜索"
                suffix={<SvgIcon icon="work-ic6" size={16} />}
                style={{
                  width: 240,
                }}
                value={searchUserValue}
                onChange={searchUser}
              />
              <div className="ml-auto flex gap-4">
                {tableSelectEdRows.length > 0 && (
                  <div className="ml-6 flex items-center gap-4 text-sm text-[#1D1D1D]">
                    <div className="font-font-weight-400 text-text-5">
                      已选择{' '}
                      <span className="font-font-weight-600">{tableSelectEdRows.length}</span> 项
                    </div>

                    <Button
                      onClick={clearTableSelectEdRows}
                      color="default"
                      variant="outlined"
                      style={{
                        background: 'var(--fill-1)',
                        borderColor: 'var(--line-2)',
                        padding: '0 12px 0px 8px',
                      }}
                      icon={<CloseCircleOutlined />}
                    >
                      取消
                    </Button>
                    <Button
                      danger
                      onClick={() => openDeleteModal('all')}
                      style={{
                        padding: '0 12px 0px 8px',
                      }}
                      // disabled={tableSelectEdRows.length === 0}
                    >
                      <SvgIcon icon="delete-outlined" size={16} />
                      删除
                    </Button>
                  </div>
                )}
                {activeValue?.system_code !== 'default' && (
                  <Button
                    onClick={() => openUpdateModal('update')}
                    style={{
                      color: 'var(--brand-color)',
                      background: '#fff',
                      borderColor: 'var(--brand-color)',
                      padding: '0 12px 0px 8px',
                    }}
                  >
                    <SvgIcon icon="add" color="var(--brand-color)" size={16} />
                    新增
                  </Button>
                )}
              </div>
            </div>
          </div>

          {userLoading ? (
            <CircleLoading />
          ) : (
            <>
              {tablesValue.length > 0 ? (
                <div className="flex h-full flex-1 flex-col">
                  <Tables
                    rowSelection={{
                      type: 'checkbox',
                      ...rowSelection,
                      selectedRowKeys: tableSelectEdRows,
                    }}
                    rowKey="id"
                    columns={columns}
                    dataSource={tablesValue}
                    pagination={false}
                    paginationProps={{
                      total: pagingInfo.total,
                      current: pagingInfo.page,
                      pageSize: pagingInfo.page_size,
                      onChange: handlePaginationChange,
                    }}
                  />
                </div>
              ) : (
                <NotData />
              )}
            </>
          )}
          {/* </>
          )} */}
        </div>
      </div>

      <UpdateModal
        open={modal.update.isOpen}
        onCancel={modal.update.close}
        onOk={updateModalSubmit}
        treeData={organiztionalModalOption}
        updateOrEdit={updateModalState}
        defaultValue={updateModalDefaultValue}
        roleList={roleList}
        confirmLoading={modal.update.isLoading}
        activeValue={activeValue}
        userSystemCode={userSystemCode}
      />

      <TipsModals
        open={modal.deleteModal.isOpen}
        onOk={deleteModalSubmit}
        onCancel={modal.deleteModal.close}
        confirmLoading={modal.deleteModal.isLoading}
      >
        {isDeleteModalState === 'org' && '确认要删除该组织，删除后无法恢复'}
        {isDeleteModalState === 'all' && `确定要删除${tableSelectEdRows.length}个用户信息?`}
        {isDeleteModalState === 'user' && '确认要删除用户信息，删除后无法恢复'}
      </TipsModals>

      <AddOrDditOrganiztionalModal
        open={modal.orgModal.isOpen}
        onCancel={modal.orgModal.close}
        onSubmitOk={organiztionalModalSubmit}
        title={treeUpdateorEditState ? '添加组织' : '编辑组织'}
        state={treeUpdateorEditState}
        defaultValue={organiztionalModalDefaultData}
        treeData={removeDefaultSystemCode(treeDataDefault)}
        confirmLoading={modal.orgModal.isLoading}
      />

      <ChangePasswordModal
        open={modal.passwordModal.isOpen}
        onOk={changePasswordModalSubmit}
        onCancel={closeChangePasswordModal}
        confirmLoading={modal.passwordModal.isLoading}
      />
    </div>
  );
};

export default OrganizationalManage;
